package com.aliyunlog.module.task.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.aliyunlog.model.ScheduleJob;
import com.aliyunlog.module.task.service.JobTaskService;
import com.aliyunlog.utils.RetObj;

@Controller
@RequestMapping("/task")
public class JobTaskController {
	// 日志记录器
	public final Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private JobTaskService taskService;

	@RequestMapping("taskList")
	public String taskList(HttpServletRequest request) {
		List<ScheduleJob> taskList = taskService.getAllTask();
		request.setAttribute("taskList", taskList);
		return "base/task/taskList";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Map<Object, Object> list(HttpServletRequest request) {
		List<ScheduleJob> taskList = taskService.getAllTask();
//		RetObj retObj = new RetObj();
//		retObj.setFlag(true);
		String draw = request.getParameter("draw");
		Map<Object, Object> info = new HashMap<Object, Object>();
	    info.put("data", taskList);
	    info.put("recordsTotal", taskList.size());
	    info.put("recordsFiltered", taskList.size());
	    info.put("draw", draw);
		return info;
	}

	@RequestMapping("add")
	@ResponseBody
	public RetObj add(HttpServletRequest request, ScheduleJob scheduleJob) {
        // 设置默认的Tracker Class
        scheduleJob.setBeanClass("com.aliyunlog.module.task.tracker.LogMonitorTracker");
        scheduleJob.setJobStatus("0"); // 默认不开启
        scheduleJob.setIsConcurrent("1"); // 默认同步
        scheduleJob.setMethodName("run"); // 默认方法名
        log.info(" scheduleJob ==> " + JSON.toJSONString(scheduleJob) );

		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		try {
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
		} catch (Exception e) {
			retObj.setMsg("cron表达式有误，不能被解析！");
			return retObj;
		}
//		Object obj = null;
//		try {
//			if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
//				obj = SpringUtils.getBean(scheduleJob.getSpringId());
//			} else {
//				Class clazz = Class.forName(scheduleJob.getBeanClass());
//				obj = clazz.newInstance();
//			}
//		} catch (Exception e) {
//			// do nothing.........
//		}
//		if (obj == null) {
//			retObj.setMsg("未找到目标类！");
//			return retObj;
//		} else {
//			Class clazz = obj.getClass();
//			Method method = null;
//			try {
//				method = clazz.getMethod(scheduleJob.getMethodName(), null);
//			} catch (Exception e) {
//				// do nothing.....
//			}
//			if (method == null) {
//				retObj.setMsg("未找到目标方法！");
//				return retObj;
//			}
//		}
		try {
			taskService.addTask(scheduleJob);
		} catch (Exception e) {
			e.printStackTrace();
			retObj.setFlag(false);
			retObj.setMsg("保存失败，检查 name group 组合是否有重复！");
			return retObj;
		}

		retObj.setFlag(true);
		return retObj;
	}

	@RequestMapping("changeJobStatus")
	@ResponseBody
	public RetObj changeJobStatus(HttpServletRequest request, Long jobId, String cmd) {
		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		try {
			taskService.changeStatus(jobId, cmd);
		} catch (SchedulerException e) {
			log.error(e.getMessage(), e);
			retObj.setMsg("任务状态改变失败！");
			return retObj;
		}
		retObj.setFlag(true);
		return retObj;
	}

	@RequestMapping("updateCron")
	@ResponseBody
	public RetObj updateCron(HttpServletRequest request, Long jobId, String cronExpression, String queryKey) {
		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		try {
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
		} catch (Exception e) {
			retObj.setMsg("cron表达式有误，不能被解析！");
			return retObj;
		}
		try {
			taskService.updateCron(jobId, cronExpression, queryKey);
		} catch (SchedulerException e) {
			retObj.setMsg("cron更新失败！");
			return retObj;
		}
		retObj.setFlag(true);
		return retObj;
	}
}
